<template>
  <div class="bg-[#fff] pt-[20px] ">

    <div class="px-[10px]">
      <el-form :model="form" :inline="true" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="py-[20px] px-[10px] bg-[#F5F5F5]">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" border height="calc(100vh - 240px)" v-loading="loading" row-key="id"
        :row-class-name="tableRowClassName" @row-click="handleRowClick">
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="name" label="名称" width="180" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="nickname" label="昵称" width="180" />
        <el-table-column prop="email" label="电子邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="salary" label="底薪" width="100" align="right" />
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" width="40" height="40" style="border-radius: 50%" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrap p-[10px]">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100, 200]"
          :disabled="disabled" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 新增编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%" :before-close="handleCancel">
      <el-form :model="dialogForm" ref="dialogFormRef" label-width="80px">
        <el-form-item label="名称" prop="name" :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]">
          <el-input v-model="dialogForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="dialogForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="dialogForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="dialogForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="dialogForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="dialogForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="dialogForm.gender" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="底薪" prop="salary">
          <el-input v-model.number="dialogForm.salary" placeholder="请输入底薪" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="handleAvatarUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="dialogForm.avatar" :src="dialogForm.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from 'vue';

// 接收父组件传递的选中领导ID
const props = defineProps({
  selectedManagerId: {
    type: [String, Number, null],
    default: null
  }
});

// 定义事件
const emit = defineEmits(['select-manager']);
import { get, post } from '@/request';
import { vToast } from '@/plugins/vToast';
import { vConfirm } from '@/plugins/vConfirm';
const form = reactive({
  name: ''
});

const currentPage = ref(1);
const pageSize = ref(20);
const disabled = ref(false);

const tableData = reactive([]);
const total = ref(0);
const loading = ref(false);

// 弹窗相关状态
const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogType = ref(''); // 'add' 或 'edit'
const dialogForm = reactive({ 
  id: '', 
  name: '',
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  gender: 1,
  salary: 0,
  avatar: ''
});
const dialogFormRef = ref(null);

// fetch data

const search = () => {
  console.log('search', form);
  currentPage.value = 1;
  loading.value = true;
  fetchData();
};

const fetchData = async () => {
  // 调用接口获取数据
  try {
    const params = {
      name: form.name,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    const res = await get('/dict/list', params);
    if (res && res.code === 200) {
      // 清空现有数据
      tableData.length = 0;
      // 添加新数据
      res.data?.list?.forEach(item => {
        tableData.push(item);
      });
      total.value = res.data?.pagination?.total || 0;
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error);
    vToast({ message: '获取管理员列表失败' });
  } finally {
    loading.value = false;
  }
};

// 编辑处理函数
const handleEdit = (row) => {
  try {
    dialogType.value = 'edit';
    dialogTitle.value = '编辑管理员';
    dialogForm.id = row.id;
    dialogForm.name = row.name || '';
    dialogForm.username = row.username || '';
    dialogForm.nickname = row.nickname || '';
    dialogForm.email = row.email || '';
    dialogForm.phone = row.phone || '';
    dialogForm.gender = row.gender || 1;
    dialogForm.salary = row.salary || 0;
    dialogForm.avatar = row.avatar || '';
    dialogVisible.value = true;
  } catch (error) {
    console.error('打开编辑弹窗失败:', error);
    vToast({ message: '打开编辑弹窗失败' });
  }
};

// 新增按钮点击事件
const handleAdd = () => {
  try {
    dialogType.value = 'add';
    dialogTitle.value = '新增管理员';
    // 清空表单
    dialogForm.id = '';
    dialogForm.name = '';
    dialogForm.username = '';
    dialogForm.nickname = '';
    dialogForm.password = '';
    dialogForm.email = '';
    dialogForm.phone = '';
    dialogForm.gender = 1;
    dialogForm.salary = 0;
    dialogForm.avatar = '';
    // 重置表单验证
    if (dialogFormRef.value) {
      dialogFormRef.value.resetFields();
    }
    dialogVisible.value = true;
  } catch (error) {
    console.error('打开新增表单失败:', error);
    vToast({ message: '打开新增表单失败' });
  }
};

// 弹窗取消按钮处理
const handleCancel = () => {
  dialogVisible.value = false;
  // 清空表单
  dialogForm.id = '';
  dialogForm.name = '';
  dialogForm.username = '';
  dialogForm.nickname = '';
  dialogForm.password = '';
  dialogForm.email = '';
  dialogForm.phone = '';
  dialogForm.gender = 1;
  dialogForm.salary = 0;
  dialogForm.avatar = '';
  // 重置表单验证
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields();
  }
};

// 弹窗提交按钮处理
const handleSubmit = async () => {
  // 表单验证
  if (!dialogFormRef.value) return;

  try {
    await dialogFormRef.value.validate();

    // 提交数据
    const params = {
      name: dialogForm.name,
      username: dialogForm.username,
      nickname: dialogForm.nickname,
      email: dialogForm.email,
      phone: dialogForm.phone,
      gender: dialogForm.gender,
      salary: dialogForm.salary,
      avatar: dialogForm.avatar
    };

    // 新增模式下需要密码
    if (dialogType.value === 'add') {
      params.password = dialogForm.password;
    }

    // 编辑模式下带上id
    if (dialogType.value === 'edit') {
      params.id = dialogForm.id;
    }

    // 根据操作类型调用不同接口
    const response = dialogType.value === 'add'
      ? await post('/dict/create', params)
      : await post('/dict/update', params);

    if (response.code === 200) {
      vToast({ message: dialogType.value === 'add' ? '新增成功' : '编辑成功' });
      dialogVisible.value = false;
      // 刷新数据列表
      fetchData();
    } else {
      vToast({ message: response.msg || (dialogType.value === 'add' ? '新增失败' : '编辑失败') });
    }
  } catch (error) {
    // 表单验证失败或接口调用失败
    if (error === false) {
      // 表单验证失败，不做处理
      return;
    }
    console.error(dialogType.value === 'add' ? '新增管理员失败:' : '编辑管理员失败:', error);
    vToast({ message: dialogType.value === 'add' ? '新增失败' : '编辑失败' });
  }
};

// 头像上传前的校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    vToast({ message: '上传头像图片只能是 JPG/PNG 格式!' });
  }
  if (!isLt2M) {
    vToast({ message: '上传头像图片大小不能超过 2MB!' });
  }
  return isJPG && isLt2M;
};

// 处理头像上传
const handleAvatarUpload = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    // 这里应该调用实际的上传接口
    // 模拟上传成功
    // const res = await post('/upload', formData);
    // if (res.code === 200) {
    //   dialogForm.avatar = res.data.url;
    // }
    
    // 由于是模拟环境，我们使用 FileReader 来读取图片本地路径
    const reader = new FileReader();
    reader.onload = (e) => {
      dialogForm.avatar = e.target.result;
    };
    reader.readAsDataURL(file);
  } catch (error) {
    console.error('上传头像失败:', error);
    vToast({ message: '上传头像失败' });
  }
};

// 删除处理函数
const handleDelete = (row) => {
  vConfirm({ message: `确定删除管理员项 ${row.name} 吗？` })
    .then(async () => {
      try {
        const response = await post('/dict/delete', { id: row.id });
        if (response.code === 200) {
          vToast({ message: '删除成功' });
          fetchData();
        } else {
          vToast({ message: response.msg || '删除失败' });
        }
      } catch (error) {
        console.error('删除管理员项失败:', error);
        vToast({ message: '删除失败' });
      }
    })
    .catch(() => { });
};

// 分页处理函数
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
  fetchData();
};

watch(() => currentPage.value, (newVal, oldVal) => {
  fetchData();
});

watch(() => pageSize.value, (newVal, oldVal) => {
  console.log('pageSize', newVal);
  fetchData();
});

// 表格行点击事件
const handleRowClick = (row) => {
  emit('select-manager', row);
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.id === props.selectedManagerId) {
    return 'selected-row';
  }
  return '';
};

// 初始加载数据
onMounted(() => {
  loading.value = true;
  fetchData();
});
</script>

<style lang="less" scoped>
.pagination-wrap {
  display: flex;
  justify-content: flex-end;
}

.selected-row {
  background-color: #e6f7ff !important;
  color: #1890ff;
  font-weight: 500;
}

/* 头像上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 148px;
  height: 148px;
}

.avatar-uploader:hover {
  border-color: #4096ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c8c8c;
  width: 148px;
  height: 148px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>